import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:day_task/models/task.dart';
import 'package:day_task/providers/task_notifier.dart';
import 'package:day_task/shared/util/background.dart';
import 'package:day_task/shared/util/loading.dart';
import 'package:day_task/shared/util/no_item.dart';
import 'package:day_task/shared/util/task_card.dart';

import '../../../shared/constants.dart';

class Body extends StatelessWidget {
  const Body({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Background(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: miDefaultSize * 1.1),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(height: miDefaultSize * 2.3),
            Consumer(builder: (context, outerRef, child) {
              final asyncTaskProvider =
                  outerRef.watch(futureTaskNotifierProvider);

              return asyncTaskProvider.when(
                data: (data) => ProviderScope(
                  overrides: [taskNotifierProvider.overrideWithValue(data)],
                  child: Consumer(
                    builder: (context, ref, child) {
                      final allTasks =
                          ref.watch(taskNotifierProvider) as List<Task>;
                      final undoneTasks = allTasks
                          .where((Task task) => task.isDone == false)
                          .toList();

                      return undoneTasks.isEmpty
                          ? NoItem(text: "没有需要标记完成的任务")
                          : Expanded(
                              child: ListView.builder(
                                physics: BouncingScrollPhysics(),
                                itemCount: undoneTasks.length,
                                itemBuilder:
                                    (BuildContext context, int index) =>
                                        TaskCard(
                                  key: ValueKey(undoneTasks[index].id),
                                  task: undoneTasks[index],
                                  isMarkDoneScreen: true,
                                ),
                              ),
                            );
                    },
                  ),
                ),
                error: (_, stack) => Center(child: Text(_.toString())),
                loading: () => const Loading(),
              );
            }),
          ],
        ),
      ),
    );
  }
}
